package main

import (
	"image"
	"image/jpeg"
	"os"
	"path"
	"strconv"
	"strings"
	"time"

	"github.com/jung-kurt/gofpdf"
)

func getPageSize(imgHeight int) (string, int, gofpdf.SizeType) {
	var paperSize string = ""
	var pageHeight int = 0
	sizeType := gofpdf.SizeType{Wd: 0, Ht: 0}
	if imgHeight%3508 == 0 {
		paperSize = "A4"
		pageHeight = 3508
	} else if imgHeight%1123 == 0 {
		paperSize = "A4"
		pageHeight = 1123
	} else if imgHeight%842 == 0 {
		paperSize = "A4"
		pageHeight = 842
	} else if imgHeight%1032 == 0 {
		pageHeight = 1032
		sizeType = gofpdf.SizeType{Wd: 197.11, Ht: 273.05}
	}
	if paperSize == "A4" {
		sizeType = gofpdf.SizeType{Wd: 210.00, Ht: 297.00}
	}
	return paperSize, pageHeight, sizeType
}
func getFileName(fullFilename string) string {
	var filenameWithSuffix string
	filenameWithSuffix = path.Base(fullFilename)
	var fileSuffix string
	fileSuffix = path.Ext(filenameWithSuffix)
	var filenameOnly string
	filenameOnly = strings.TrimSuffix(filenameWithSuffix, fileSuffix)
	return filenameOnly
}

func main() {
	var src string = ""
	var pdfFileName = ""
	for k, v := range os.Args {
		if k == 1 {
			src = v
		}
		if k == 2 {
			pdfFileName = v
		}
	}
	if pdfFileName == "" {
		pdfFileName = getFileName(src) + ".pdf"
	}
	imgFile, err := os.Open(src)
	defer imgFile.Close()
	img, err := jpeg.Decode(imgFile)
	imgHeight := int(img.Bounds().Dy())
	imgWidth := int(img.Bounds().Dx())
	paperSize, pageHeight, sizeType := getPageSize(imgHeight)
	pageNum := int(imgHeight / pageHeight)
	// 创建一个新的pdf文件
	init := gofpdf.InitType{
		OrientationStr: "p",
		UnitStr:        "mm",
		SizeStr:        paperSize,
		Size:           sizeType,
		FontDirStr:     "",
	}

	pdf := gofpdf.NewCustom(&init)
	startX := 0
	startY := 0
	endX := startX + imgWidth
	endY := startY + pageHeight
	var canvas image.Image
	canvas = img
	var opt jpeg.Options
	opt.Quality = 100
	// 循环读取需要转换的图片
	imgCanvas := canvas.(*image.YCbCr)
	for i := 0; i < pageNum; i++ {
		subImageFile := strconv.Itoa(time.Now().Nanosecond()) + ".jpg"
		fOut, _ := os.Create(subImageFile)
		// 添加一个新的页面
		pdf.AddPage()
		subImg := imgCanvas.SubImage(image.Rect(startX, startY, endX, endY)).(*image.YCbCr)
		jpeg.Encode(fOut, subImg, &opt)
		pdfPageWidth, pdfPageHeight := pdf.GetPageSize()
		pdf.Image(subImageFile, 0, 0, pdfPageWidth, pdfPageHeight, false, "", 0, "")
		fOut.Close()
		os.Remove(subImageFile)
		startY += pageHeight
		endY += pageHeight
	}
	// 输出pdf文件
	err = pdf.OutputFileAndClose(pdfFileName)
	if err != nil {
		panic(err)
	}
}
